package com.etc.shiro;

import com.etc.shiro.model.AuthMst;
import com.etc.shiro.model.RoleMst;
import com.etc.shiro.model.UserMst;
import com.etc.shiro.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


public class EnceladusShiroRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    // za授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String username = (String) principals.getPrimaryPrincipal();

        UserMst user = userService.findUserByName(username);

        for (RoleMst role : user.getRlist()) {
            authorizationInfo.addRole(role.getRname());
            for (AuthMst permission : role.getPlist()) {
                authorizationInfo.addStringPermission(permission.getAuth());
            }
        }
        return authorizationInfo;
    }

    /**
     * 鉴权
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
//        String password = new String(((UsernamePasswordToken)token).getPassword());
        UserMst user = userService.findUserByName(username);

        // DB中的密码和  input的密码 加密后再比较

        if (user == null) {
//            return null;
            throw new UnknownAccountException();
        }

        //返回安全数据
        // input --->  TOM  __DB__ TOM/密码/salt
        // 验证     tom----密码  ---salt是否一致
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUname(), user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()), getName());

        // 权限信息
        return authenticationInfo;

    }


    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }

    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }

}
